package com.dgz.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.dgz.common.core.constants.Constants;
import com.dgz.common.core.constants.HttpConstants;
import com.dgz.common.core.uitls.ThreadLocalUtil;
import com.dgz.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2024/12/10/9:39
 * @Description:
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secret;  // 从那个服务的配置文件中读取 取决于交个那个服务的容器进行管理

    @Autowired
    private TokenService tokenService;

    // 执行controller之前调用   用于token的延长  token永不过期，延长的是redis中存储的token的过期时间
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if(StrUtil.isEmpty(token)) {
            return true;
        }
        Long userId = tokenService.getUserId(token, secret);
        String userKey = tokenService.getUserKey(token, secret);
        ThreadLocalUtil.set(Constants.USER_ID,userId); // 将当前操作的用户id存入到本地线程变量中
        ThreadLocalUtil.set(Constants.USER_KEY,userKey); // 将当前操作的用户key存入到本地线程变量中
        tokenService.extendToken(token,secret);
        return true;
    }


    // 执行controller之后调用   用于清除本地线程变量
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }


    private String getToken(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }


}
